<?php

	session_start();
	/**
	* @package admin
	* @desc Validation checks for editing park info and uploading image file before saving edited details.
	*/

	// Direct calling check
	if(!isset($_SESSION["role"]))
	{
		header('Location: ../index.php');
		exit();
	}
	if($_SESSION["role"] != "admin")
	{
		header('Location: ../index.php');
		exit();
	}
	if(!isset($_POST["submit"]))
	{
		header('Location: findpark.php');
		exit();
	}
	
	if($_POST['submit'] == "Cancel")
	{		
		header("Location: parks.php");
		exit();
	}

	/**
	* @desc This include file connects to the database.
	*/
	require '../includes/connect.inc';	

	// Make arrays
	$_SESSION["errors"] = array();
	$_SESSION["form"] = array();

	$suburb_id = $_POST["suburb"];
	$park_type = $_POST["type"];
	$park_name = $_POST["name"];
	$park_address = $_POST["address"];
	
	// Name validation	
	if(!empty($park_name))
	{
		if (!preg_match('/^[a-zA-Z0-9\s&\/,]+$/', $park_name))
			$_SESSION["errors"]["name"] = "No numbers allowed";
		else if (strlen($park_name) > 40)
			$_SESSION["errors"]["name"] = "Maximum 40 characters";
		else
			$_SESSION["form"]["name"] = $park_name;
	}
	else
	{
		$_SESSION["errors"]["name"] = "Name cannot be empty";
	}
	
	//Address validation
	if(!empty($park_address))
	{
		if (!preg_match('/^[a-zA-Z0-9\s&\/,]+$/', $park_address))
			$_SESSION["errors"]["address"] = "No numbers allowed";
		else if (strlen($park_address) > 50)
			$_SESSION["errors"]["address"] = "Maximum 50 characters";
		else
			$_SESSION["form"]["address"] = $park_address;
	}
	else
	{
		$_SESSION["errors"]["address"] = "Address cannot be empty";
	}
	
	//park type validation
	if(!empty($park_type))
	{
		if (!preg_match('/^[a-zA-Z\s]+$/', $park_type))
			$_SESSION["errors"]["type"] = "No numbers allowed";
		else if (strlen($park_type) > 30)
			$_SESSION["errors"]["type"] = "Maximum 30 characters";
		else
			$_SESSION["form"]["type"] = $park_type;
	}
	else
	{
		$_SESSION["errors"]["type"] = "Type cannot be empty";
	}
	
	if(count($_POST["park_equip"]))
	{
		for($i = 0; $i < count($_POST["park_equip"]); $i++)
		{
			if(!empty($_POST[$_POST["park_equip"][$i]]))
			{
				if(!preg_match('/^[0-9]+$/', $_POST[$_POST["park_equip"][$i]]))
					$_SESSION["errors"][$_POST["park_equip"][$i]] = "Only numbers allowed";
				else if(strlen($_POST[$_POST["park_equip"][$i]]) > 11)
					$_SESSION["errors"][$_POST["park_equip"][$i]] = "Maximum 11 digits";
			}
			else
			{
				$_SESSION["errors"][$_POST["park_equip"][$i]] = "Field cannot be empty";
			}
			$_SESSION["form"][$_POST["park_equip"][$i]] = $_POST[$_POST["park_equip"][$i]];
		}
	}
	
	//---------------------------------------------------------------------------------------------------
	//image validations
	if($_FILES['pic']['size'] > 0)
	{
		$pic_name = trim(sql_safe($_FILES['pic']['name']));
		$pic_type = trim(sql_safe($_FILES['pic']['type']));
		$pic_size = trim(sql_safe($_FILES['pic']['size']));
	
		list(, , $imgtype, ) = getimagesize($_FILES['pic']['tmp_name']);
	
		if($imgtype == 3) // cheking image type
			$type = "png";
		else if($imgtype == 2)
			$type = "jpeg";
		else if($imgtype == 1)
			$type = "gif";
		else
			$_SESSION["errors"]["pic"] = "Unsupported image file";
	}	
	
	// If there were any errors, show the page again
	if (count($_SESSION["errors"]))
	{
		header("Location: addpark.php");
		exit();
	}
	
	//prepare query for park insert
	$parks_query = "INSERT INTO parks (park_id, suburb_id, type, name, address) VALUES(NULL, '".$suburb_id."', '".$park_type."', '".$park_name."', '".$park_address."')";
	
	//run query
	mysql_query($parks_query, $connection) or die("Could not insert park details");
	
	//get park id
	$query = "SELECT park_id FROM parks WHERE name = '".$park_name."'";
	$result = mysql_query($query, $connection) or die("Could not get new park id");
	
	$row = mysql_fetch_array($result);
	$park_id = $row['park_id'];
	
	if($_FILES['pic']['size'] > 0)
	{
		$file = file_get_contents($_FILES['pic']['tmp_name']);
		$file = mysql_real_escape_string($file);
		
		// Preparing data to be used in MySQL query
		$query = "INSERT INTO pictures (id, name, type, size, file) VALUES($park_id, '$pic_name', '$type', $pic_size, '$file')";
		
		mysql_query($query, $connection) or die("Could not update park picture");
	}
	
	for($i = 0; $i < count($_POST["park_equip"]); $i++)
	{
		$query = "INSERT INTO parkequipment (park_id, equip_id, qty) VALUES($park_id,".$_POST["park_equip"][$i].", ".$_POST[$_POST["park_equip"][$i]].")";
		mysql_query($query, $connection) or die("Could not update equipment".$_POST["park_equip"][$i]."insert");
	}
		
	mysql_close($connection); // Disconnect
	
	unset($_SESSION["form"]);
	unset($_SESSION["errors"]);
	header("Location: ../parkdetails.php?id=$park_id");
	
	
	//-------------------------------------------------------------------------------------------
	
	/**
	*@desc Function sanitize SQL entries, preventing sql injection.
	*@param string $s
	*/
	function sql_safe($s)
	{
		if (get_magic_quotes_gpc())
			$s = stripslashes($s);
		return mysql_real_escape_string($s);
	}
	
	//-------------------------------------------------------------------------------------------
	
?>